package routes

import (
	"etcd/controller"
	"etcd/e"
	"etcd/utile"
	"fmt"
	"github.com/gin-gonic/gin"
	"strings"
)

func loadAdminRoute() {
	r.POST("/login", controller.Login)
	manager := r.Group("/admin")
	manager.Use(LoginMiddleWare())
	{

		manager.GET("/system-init", controller.SystemInit)

		manager.GET("/menu", controller.Menu)

		manager.POST("/etcd/reset-password", controller.EtcdResetPassword)

		manager.POST("/etcd/get", controller.EtcdGet)

		manager.POST("/etcd/set", controller.EtcdSet)

		manager.POST("/etcd/del", controller.EtcdDelKey)

		manager.POST("/etcd/key/list", controller.EtcdGetAllKeys)

		manager.POST("/etcd/sys/conf", controller.LogSysConf)

		manager.POST("/etcd/sys/add-key", controller.AddSysConfKey)

		manager.POST("/etcd/sys/del-key", controller.DelSysConfKey)

		manager.POST("/etcd/sys/info", controller.GetSysConfInfoByKey)

		manager.POST("/etcd/sys/save", controller.EtcdSaveSysConf)
	}
}

// 定义中间
func LoginMiddleWare() gin.HandlerFunc {
	return func(c *gin.Context) {
		//t := time.Now()
		//fmt.Println("中间件开始执行了")
		// 设置变量到Context的key中，可以通过Get()取
		//c.Set("request", "中间件")
		//status := c.Writer.Status()
		//fmt.Println("中间件执行完毕", status)
		//t2 := time.Since(t)
		//fmt.Println("time:", t2)
		//c.Header("authorization", "Bearer "+token)
		//获取request中的token，做权限验证
		token := c.GetHeader("Authorization")
		if token != "" && strings.Contains(token,"Bearer") {
			token = strings.Trim(token,"Bearer")
			token = strings.Trim(token," ")
		}
		tokenBag,err := utile.ParseToken(token)
		if err != nil {
			// 验证不通过，不再调用后续的函数处理
			c.Abort()
			controller.Error(c,e.ERROR_PARSE_TOKEN)
			return
		}
		fmt.Println(tokenBag)
		c.Header("authorization", "Bearer "+token)
		c.Next()
	}
}